// pages/confirmorder/confirmorder.js
const app = getApp();
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		ID: false,
		addr: {
			name: '',
			phone: '',
			addr: ''
		},

		types: [
			{ id: '1', img: "/images/weixin.png", typeName: "微信支付", checked: "true" },
			{ id: "2", img: "/images/xxzf.png", typeName: "余额支付", }
		],
		foods: {},
		tableid: '',
		cart: [],
		food: [],
		znum: 0,
		zprice: 0,
		preafterprice: 0,
		leveMoney: 0,
		checked1: false,
		pstype: '1',
		textareavalue: '',
		phonevalue: '',
		coupon: {},
		collage: '',
		collage_goods: [],
		points: {},
		integral: 0,
		integralpri: 0,
		yhq: {
			id: null,
			name: '不使用优惠券',
			pri: 0
		},
		orderdd: {},//提交的时候的订单
		bool: false,
	},
	radioChange: function (e) {
		this.setData({
			pstype: e.detail.value
		})
	},

	textareachange: function (e) {
		this.setData({
			textareavalue: e.detail.value
		})
	},
	phonevalue: function (e) {
		this.setData({
			phonevalue: e.detail.value
		})
	},
	addr: function () {
		var that = this;
		wx.chooseAddress({
			success: function (res) {
				that.setData({
					'addr.name': res.userName,
					'addr.phone': res.telNumber,
					'addr.addr': res.provinceName + res.cityName + res.countyName + res.detailInfo,
				})
			},
			fail: function (res) {
				wx.getSetting({
					success(res) {
						if (!res.authSetting['scope.address']) {
							wx.authorize({
								scope: 'scope.address',
								success(res) {
								},
								fail: function (res) {
									wx.openSetting({
										success: (res) => {
											if (!res.authSetting["scope.address"]) {
												wx.showModal({
													title: '提示',
													content: '通讯地址授权失败，不能使用外卖',
													showCancel: false,
													success: function (res) {
														if (res.confirm) {
															that.setData({
																pstype: 1
															})
														}
													}
												})
											}
										}
									})
								}
							})
						}
					}
				})
			}
		})
	},

	/*总的价格数量 */
	znumprice: function () {
		var znum = 0;
		var zprice = 0;
		if (this.data.ID == false) {
			this.data.cart.forEach(function (item, index) {
				znum += item.num
				zprice += item.price * item.num
			})
			if (znum > 99) {
				znum = '99+'
			}
			this.setData({
				znum: znum,
				zprice: zprice,
			})
		}

	},
	/* 选择优惠券*/
	chooseyh: function (e) {
		var that = this;
		if (that)
			if (that.data.coupon.data.length == 0) {
				wx.showToast({
					title: '您暂无可使用的优惠券',
					icon: 'none',
					duration: 2000
				})
        that.setData({
          "yhq.name":"您暂无可用的优惠券"
        })
				return false;
			} else {
				wx.navigateTo({
					url: '../myYouhui/myYouhui?id=0',
				})
			}
	},
	/*优惠后的价格*/
	preafterprice: function () {
		var that = this;
		var order = {};
		var food = [];
		var yhqid = null;
		if (that.data.ID == false) {
			that.data.cart.forEach(function (item) {
				var spec = '';
				food.push({ food_id: item.goodid, spec_item: spec, count: item.num })
			})
		} else {
			var foods = that.data.foods;
			food.push({ food_id: foods.goods_id, count: 1 })
		}

		if (parseInt(that.data.yhq.id)) {
			order = {
				price: that.data.zprice,
				true_price: that.data.preafterprice,
				coupon_id: parseInt(that.data.yhq.id),
				note: that.data.textareavalue,
				phone: that.data.addr.phone,
				food: food,
				type: parseInt(that.data.pstype),
				address: that.data.addr.addr,
				name: that.data.addr.name,
			}
		} else {
			order = {
				price: that.data.zprice,
				true_price: that.data.preafterprice,
				note: that.data.textareavalue,
				phone: that.data.addr.phone,
				food: food,
				type: parseInt(that.data.pstype),
				address: that.data.addr.addr,
				name: that.data.addr.name,
			}
		}

		if (that.data.colllage != '') {
			order.collage = that.data.collage;
		}

		that.setData({
			orderdd: order
		})
		var type = order.type
		wx.request({
			url: app.globalData.directory + 'api/v2/pay/handle_price/' + type,
			method: 'POST',
			data: order,
			header: {
				'content-type': 'application/json',
				'token': wx.getStorageSync('token')
			},
			success: function (res) {
				if (res.data.status == 'ok') {
					that.setData({
						preafterprice: res.data.data,
						'orderdd.true_price': res.data.data
					})
					if (that.data.bool) {

						that.pay();
					}
				} else {
					wx.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000,
					})
				}
			}
		})
	},
	/*支付 */
	pay: function () {
		var that = this;
		var preafterprice = that.data.preafterprice;
		var leveMoney = that.data.leveMoney;
		var pstype = that.data.pstype
		var cart2 = wx.getStorageSync('cart1');
    // console.log(cart2,"我是cart1的缓存代号:cart2")
		wx.setStorageSync('shopcar', cart2);
    console.log(wx.getStorageSync('shopcar'),'我是cart2的缓存代号:shopcar')
		wx.request({
			url: app.globalData.directory + 'api/v2/pay/order_pay',
			method: 'POST',
			data: that.data.orderdd,
			header: {
				'content-type': 'application/json',
				'token': wx.getStorageSync('token')
			},
			
			success: function (res) {
				//
				wx.request({
					url: app.globalData.directory + 'api/v2/pay/facepay',
					header: {
						'content-type': 'application/json',
						'token': wx.getStorageSync('token')
					},
					success: function (res) {
						// console.log(res)
						if (res.errMsg == 'request:ok') {
							app.globalData.coupon = res.data.coupon;
							app.globalData.points = res.data.points;

						} else {
							wx.showToast({
								title: '请求失败,请重试',
								icon: 'none',
								duration: 2000,
							})
						}
					}
				})
				if (pstype == "1") {
					if (res.data.status == 'ok') {
						if (res.data.msg == 'success') {
							wx.requestPayment({
								'timeStamp': res.data.data.timestamp,
								'nonceStr': res.data.data.nonceStr,
								'package': res.data.data.package,
								'signType': res.data.data.signType,
								'paySign': res.data.data.paySign,
								'success': function (res) {
									setTimeout(function () {
										wx.redirectTo({
                    
											url: '../dingdan/dingdan?id=2',
										})
									}, 1000)
								},
								'fail': function (res) {
									console.log(res)
									wx.showToast({
										// title: res.errMsg,
                    title:'未付款',
										icon: 'none',
										duration: 2000,
									})
									setTimeout(function () {
										wx.redirectTo({
											url: '../dingdan/dingdan?id=1',
										})
									}, 1000)
                  // wx.removeStorageSync('shopcar')
                  // wx.removeStorageSync('cart')
                  // wx.removeStorageSync('cart1')
                  // wx.setStorageSync('shopcar', [])
                  // wx.setStorageSync('cart', [])
                  // wx.setStorageSync('cart1', [])
								}
							})
						}
					} else {
						wx.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 2000,
						})

					}
				} else {
					// console.log(res.data.status,"******")
					if (res.data.status == "ok") {
						if (res.data.msg == "success") {
							wx.request({
								url: app.globalData.directory + 'api/v2/user/getuser',
								method: "POST",
								data: that.data.orderdd,
								header: {
									'content-type': 'application/json',
									'token': wx.getStorageSync('token')
								},
								success: function (res) {
									if (res.data.status == "ok") {
										wx.showToast({
											title: '支付成功',
											icon: 'success',
											duration: 1000,
										})
										setTimeout(function () {
											wx.redirectTo({
												url: '../dingdan/dingdan?id=2',
											})
										}, 1000)
									}
								}
							})
						}
					} else {
						wx.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 2000,
						})
						wx.showModal({
							title: '提示',
							content: '余额不足，是否去充值',
							success: function (res) {
								if (res.confirm) {
									wx.navigateTo({
										url: '../toRecharge/toRecharge',
									})
								} else {
									setTimeout(function () {
										wx.redirectTo({
											url: '../dingdan/dingdan?id=1',
										})
									}, 1000)
								}
							}
						})
					}
				}
			}
		})
	},
	/*提交表单 */
	bindsub: function () {
		this.setData({
			bool: true
		})
		this.preafterprice();
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (option) {
    // console.log(wx.getStorageSync('cart'),"2222222222")
		if (option.id !== "undefined") {
			this.setData({
				cart: wx.getStorageSync('cart'),
				coupon: app.globalData.coupon,
				ID: true
			})
			var that = this
			wx.request({
				url: app.globalData.directory + 'api/v2/getCollageDetails/' + option.id,
				header: {
					'content-type': 'application/json', // 默认值
					'token': wx.getStorageSync('token')
				},
				success: function (res) {
					if (res.data.status == "ok") {
						var foods = that.data.foods;
						foods = res.data.data;
						that.data.collage = res.data.data.id;

						that.setData({
							foods: foods
						})

					} else {
						wx.showToast({
							title: '请求失败,请重试',
							icon: 'none',
							duration: 2000,
						})
					}
				}
			})
			if (parseInt(app.globalData.choosewelfare) == 0) {
				that.setData({
					'yhq.id': null,
					'yhq.name': '不使用优惠券',
					'yhq.pri': 0,
				})
				that.znumprice();
				return false;
			}
			if (parseInt(app.globalData.choosewelfare)) {
				that.data.coupon.data.forEach(function (item, index) {
					if (item.id == app.globalData.choosewelfare) {
						that.setData({
							'yhq.id': item.id,
							'yhq.name': item.name,
							'yhq.pri': item.amount_cash,
						})
					}
				})
			}
			this.znumprice();

		} else {
			var that = this;
			this.setData({
				cart: wx.getStorageSync('cart'),
				coupon: app.globalData.coupon,
				leveMoney: app.globalData.leavMoney,
				ID: false
			})
			wx.request({
				url: app.globalData.directory + 'api/v2/getGoodsAll',
				header: {
					'content-type': 'application/json',
					'token': wx.getStorageSync('token')
				},
				success: function (res) {
					if (res.data.status == 'ok') {
						that.setData({
							foods: res.data.data
						})
					} else {
						wx.showToast({
							title: '请求失败,请重试',
							icon: 'none',
							duration: 2000,
						})
					}
				}
			})

			if (parseInt(app.globalData.choosewelfare) == 0) {
				that.setData({
					'yhq.id': null,
					'yhq.name': '不使用优惠券',
					'yhq.pri': 0,
				})
				that.znumprice();
				return false;
			}
			if (parseInt(app.globalData.choosewelfare)) {
				that.data.coupon.data.forEach(function (item, index) {
					if (item.id == app.globalData.choosewelfare) {
						that.setData({
							'yhq.id': item.id,
							'yhq.name': item.name,
							'yhq.pri': item.amount_cash,
						})
					}
				})
			}
		}
		this.znumprice();
		// this.integral();
		// this.preafterprice();

    wx.setStorageSync('priceszong', this.data.zprice)
    // console.log(wx.getStorageSync('priceszong'),'********')
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
    // console.log(app.globalData.yhqName)
		var that = this;
		if (parseInt(app.globalData.choosewelfare) == 0) {
			that.setData({
				'yhq.id': null,
				'yhq.name': '不使用优惠券',
				'yhq.pri': 0,
			})

			return false;
		}
    // else{
    //   that.setData({
    //     'yhq.name': app.globalData.yhqName
    //   })
    // }
		if (parseInt(app.globalData.choosewelfare)) {
			that.data.coupon.data.forEach(function (item, index) {
				if (item.id == app.globalData.choosewelfare) {
					that.setData({
						'yhq.id': item.id,
						'yhq.name': item.name,
						'yhq.pri': item.amount_cash,
					})

				}
			})
		}else{
      that.setData({
        "yhq.name":app.globalData.yhqName
      })
    }
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})